package com.duoduo.链表;

import com.duoduo.ListNode;

/**
 * @program: algorithm
 * @description: 删除链表的倒数第N个结点19
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 * @author: chaidl  ！
 * @create: 2022-05-17 21:35
 */
public class 删除链表的倒数第N个结点19 {
	public static void main(String[] args) {
		ListNode root = new ListNode(1);
		root.next = new ListNode(2);
		root.next.next = new ListNode(3);
		root.next.next.next = new ListNode(4);
		root.next.next.next.next = new ListNode(5);
		ListNode node = new 删除链表的倒数第N个结点19().removeNthFromEnd(root,2);
		System.out.println(node);

	}
	public ListNode removeNthFromEnd(ListNode head, int n) {
		ListNode result=new ListNode(0);
		ListNode slow=result,fast=result;
		fast.next=head;
		for (int i = 0; i <= n; i++) {
			fast=fast.next;
		}
		while (fast!=null){
			fast = fast.next;
			slow=slow.next;
		}
		slow.next = slow.next.next;
		return result.next;
	}
}
